package com.op.teachingliteapp.fragment.smartpan;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.example.android_file_manger.MainActivity;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.FileBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.ApiConstant;
import com.op.teachingliteapp.common.api.smartpan.CmdForm;
import com.op.teachingliteapp.common.api.smartpan.EntityBean;
import com.op.teachingliteapp.util.DirUtils;
import com.op.teachingliteapp.util.FileUtils;
import com.op.teachingliteapp.util.SharedPreferencesUtils;
import com.op.teachingliteapp.util.SmartPanUtils;
import com.op.teachingliteapp.util.ToastUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

public class SmartPanFragment extends Fragment {
	private Button mySmartPan, courseSmartPan, back;
	private ListView mySmartPanFile;
	private List<FileBean> fileBean;
	private String path, getUserId;
	private SmartPanListviewAdapter adapter;
	public static EditText mySmartPanFileChoose;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		// 该Fragment的布局
		View root = inflater.inflate(R.layout.fragment_smart_pan, container, false);
		mySmartPanFile = (ListView) root.findViewById(R.id.my_smart_pan_file);
		mySmartPan = (Button) root.findViewById(R.id.my_smart_pan);
		courseSmartPan = (Button) root.findViewById(R.id.course_smart_pan);
		ImageButton synchronous = (ImageButton) root.findViewById(R.id.synchronous);
		ImageButton createNewfile = (ImageButton) root.findViewById(R.id.create_newfile);
		CheckBox allChoose = (CheckBox) root.findViewById(R.id.smart_pan_file_allchoose);
		// 设置云盘按钮图片
		courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan_normal);
		mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_selected);
		back = (Button) root.findViewById(R.id.back);
		ImageButton mySmartPanFilePush = (ImageButton) root.findViewById(R.id.my_smart_pan_file_push);
		// 获取用户Id
		getUserId = SharedPreferencesUtils.get(Common.Prefs.USER_ID, getActivity());
		path = Common.rootFilePath.ROOT_FILE_PATH + getUserId;
		adapter = getAdapter(path);
		// 设置listview的adapter
		mySmartPanFile.setAdapter(adapter);
		// item监听
		mySmartPanFile.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// 如果点击的是文件夹 则进入
				if (!adapter.isFile(position)) {
					path += "/" + adapter.getFileName(position);
					localRefreshList(path);
				} else {
				}
			}
		});
		/**
		 * 全选按钮监听
		 */
		allChoose.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				Map<String, Object> prefsMap = new HashMap<String, Object>();
				if (isChecked) {
					prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, true);
				} else {
					prefsMap.put(Common.Prefs.DROP_DOWN_BUTTON_CONDITION, false);
				}
				SharedPreferencesUtils.put(getActivity(), prefsMap);
				adapter.setList(fileBean);
				adapter.notifyDataSetChanged();
			}
		});

		/**
		 * 上传按钮监听
		 */
		mySmartPanFilePush.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				// 上传文件的dialog的布局以及控件
				final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();

				alertDialog.show();
				Window window = alertDialog.getWindow();
				window.setContentView(R.layout.my_smart_pan_dialog);
				mySmartPanFileChoose = (EditText) window.findViewById(R.id.smart_pan_file_path);
				// dialog的上传按钮监听
				window.findViewById(R.id.file_push).setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						pushFileAndGetFilePath();
					}
				});
				// 选择要添加的文件的按钮监听
				mySmartPanFileChoose.setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						pushFileAndGetFilePath();
					}

				});
				// 确定按钮监听
				window.findViewById(R.id.push_file_determine).setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						String path = mySmartPanFileChoose.getText().toString();
						File file = new File(path);
						if (!file.isFile()) {
							ToastUtils.show(getActivity(), "请选择文件");
						} else {
							ToastUtils.show(getActivity(), file.getName());
						}

					}
				});
				// 取消按钮监听
				window.findViewById(R.id.push_file_cancel).setOnClickListener(new OnClickListener() {
					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});
			}
		});
		/**
		 * 新建文件夹按钮监听
		 */
		createNewfile.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
				alertDialog.show();
				Window window = alertDialog.getWindow();
				window.setContentView(R.layout.create_folder_dialog);
				// 实例化按钮和文件输入地址
				TextView createFolderTitle = (TextView) window.findViewById(R.id.create_folder_dialog_title);
				createFolderTitle.setText("新建文件夹");
				final EditText createFolderPath = (EditText) window.findViewById(R.id.create_folder_dialog_path);
				alertDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
				window.findViewById(R.id.create_folder_cancel).setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						alertDialog.dismiss();
					}
				});
				// 确定按钮监听
				window.findViewById(R.id.create_folder_determine).setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						final String fileName = createFolderPath.getText().toString();
						final String ownerId = SharedPreferencesUtils.getInstance(getActivity()).getString(Common.Prefs.USER_ID, "");

						// path后如果没有"/",记得加"/"
						String cmdJson = CmdForm.generateJsonCmd(ownerId, SmartPanUtils.localConversionSend(path, getActivity()), CmdForm.CMD_CREATE_FOLDER, fileName);
						List<NameValuePair> params = new ArrayList<NameValuePair>();
						params.add(new BasicNameValuePair("CMD", cmdJson));
						HttpPostTask task = new HttpPostTask(getActivity(), ApiConstant.SMART_PAN_URL, params);
						task.setTaskListener(new OnTaskProcessListener() {
							public void prepare() {
							}

							public void completed(String result) {

								Log.i("-----", result);
								String msg = CmdForm.getOutputMessage(result);
								if (msg.equals("create folder sucess")) {
									Log.i("-----", SmartPanUtils.localConversionSend(path, getActivity()) + "/" + fileName + "/");
									boolean isSuccess = FileUtils.makeDirs(Common.rootFilePath.ROOT_FILE_PATH + ownerId + "/" + SmartPanUtils.localConversionSend(path, getActivity()) + "/" + fileName + "/");
									if (isSuccess) {
										ToastUtils.show(getActivity(), "文件夹创建成功");
										fileBean = new DirUtils(getActivity(), getUserId).getFileList(Common.rootFilePath.ROOT_FILE_PATH + ownerId + "/" + SmartPanUtils.localConversionSend(path, getActivity()));
										adapter.setList(fileBean);
										adapter.notifyDataSetChanged();
									} else {
										ToastUtils.show(getActivity(), "文件夹创建失败");
									}
									localRefreshList(path);
								} else {
									ToastUtils.show(getActivity(), "文件夹创建失败，文件夹已存在");
								}
								alertDialog.dismiss();
							}

						});
						task.execute();

					}
				});

			}
		});
		/**
		 * 我的云盘按钮监听
		 */
		mySmartPan.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan_normal);
				mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_selected);
				path = Common.rootFilePath.ROOT_FILE_PATH + getUserId;
				localRefreshList(path);
			}
		});
		/**
		 * 课程云盘按钮监听
		 */
		courseSmartPan.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				path = Common.rootFilePath.ROOT_FILE_PATH + getUserId + "/Course";
				localRefreshList(path);
				courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan_selected);
				mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_normal);
			}
		});
		/**
		 * 同步按钮监听
		 */
		synchronous.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				fileBean = new DirUtils(getActivity(), getUserId).getFileList(path);

				String cmdJson = CmdForm.generateJsonCmd(getUserId, SmartPanUtils.localConversionSend(path, getActivity()), CmdForm.CMD_LIST);
				// 发送POST请求给ApiConstant.SMART_PAN_URL
				getPostResult(cmdJson);
			}
		});
		/**
		 * 返回上一级按钮监听
		 */
		back.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// 获取上一级地址
				int backwhere = path.lastIndexOf("/");
				if (!path.equals(Common.rootFilePath.ROOT_FILE_PATH + getUserId)) {
					path = path.substring(0, backwhere);
					Log.i("SmartPanFragment", "上一级路径：" + path);
					Log.i("SmartPanFragment", "上一级路径长度：" + backwhere);
				}
				if (path.equals(Common.rootFilePath.ROOT_FILE_PATH + getUserId)) {
					courseSmartPan.setBackgroundResource(R.drawable.course_smart_pan_normal);
					mySmartPan.setBackgroundResource(R.drawable.my_smart_pan_selected);
				}
				localRefreshList(path);
			}
		});
		new DirUtils(getActivity(), getUserId).getFilesNameByDir("Course");
		return root;
	}

	/**
	 * 获取对应路径的文件adapter
	 */
	public SmartPanListviewAdapter getAdapter(String path) {
		Log.i("getadapter", "getadapter" + path);
		fileBean = new DirUtils(getActivity(), getUserId).getFileList(path);
		 // 判断是不是空文件夹,如果是空文件夹，则返回一个新的空adapter
		 if (!(fileBean != null && !fileBean.isEmpty())) {
		 fileBean = new ArrayList<FileBean>();
		 }
		adapter = new SmartPanListviewAdapter(getActivity(), fileBean, path);
		return adapter;
	}

	public void getPostResult(String cmdJson) {
		// 做异步请求
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("CMD", cmdJson));
		HttpPostTask task = new HttpPostTask(getActivity(), ApiConstant.SMART_PAN_URL, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				Log.i("SmartPanFragment", "同步返回数据: " + result);

				List<EntityBean> entityBeanList = new ArrayList<EntityBean>();
				if (CmdForm.fillEntityBeanList(entityBeanList, result)) {
					System.out.println("获取到的Size为: " + entityBeanList.size());
				} else {
					System.out.println("路径有问题");
				}

				// 本地数据库与云盘对比
				fileBean = SmartPanUtils.localWithSmartPanContrast(fileBean, entityBeanList);
				// 云盘与本地对比
				fileBean = SmartPanUtils.SmartPanContrastWithlocal(fileBean, entityBeanList, getActivity());

				adapter.setList(fileBean);
				adapter.notifyDataSetChanged();
			}

		});
		task.execute();
	}

	/**
	 * 上传选定文件获得文件路径
	 */
	public void pushFileAndGetFilePath() {
		Intent intent;
		intent = new Intent(getActivity(), MainActivity.class);
		startActivity(intent);
	}

	/**
	 * 列表adapter刷新
	 */
	public void localRefreshList(String path) {
		adapter = getAdapter(path);
		adapter.notifyDataSetChanged();
		mySmartPanFile.setAdapter(adapter);
	}

}
